/**
 * @file   dir.hpp
 * @author wolfhead <wolfhead@wolfhead-laptop>
 * @date   Thu Nov 10 21:48:13 2011
 * 
 * @brief  
 * 
 * 
 */
#ifndef ACAPELLA_UTIL_DIR_HPP
#define ACAPELLA_UTIL_DIR_HPP

#include <sys/types.h>
#include <dirent.h>
#include "../shared_ptr.hpp"

namespace acapella
{
namespace util
{

class DirEntry : public dirent
{
public:
    const char * GetName() {return d_name;}
    unsigned char GetType() {return d_type;}
    unsigned short GetRecordLength() {return d_reclen;}
};

class Dir
{
public:
    typedef acapella::shared_ptr< ::DIR*, DirContent> DIR;
    typedef std::vector<DirEntry> DirEntryList;

    Dir(const std::string& path)
        :dir_(_OpenDir(path))
    {
    }

    int ReadDir(DirEntryList& list)
    {
        if (!dir_)
        {
            return -1;
        }

        DirEntry entry;
        dirent * p = NULL;
        do
        {
            if (0 != readdir_r(dir_.get(), &entry, &p))
            {
                break;
            }
            list.push_back(entry);
            
        } while (p != NULL);

        rewinddir(dir_);

        return 0;
    }

    operator bool () const
    {
        return bool(dir_);
    }

private:

    DIR _OpenDir(const std::string& path)
    {
        return DIR(opendir(path.c_str()));
    }

    DIR dir_;
};



}//namespace util
}//namespace acapella

#endif // #ifndef ACAPELLA_UTIL_DIR_HPP
